package com.kxn.controller;

import java.io.File;
import java.io.IOException;

import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.kxn.model.HomeModel;
import com.kxn.service.IHomeService;
import com.kxn.service.SpitterService;

@Controller
@RequestMapping("/")
public class HomeController{
	public static final int DEFAULT_SPITTLES_PER_PAGE = 25;
	
	@Autowired
	private IHomeService homeService;
	
	@Autowired
	private SpitterService spittleService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String showHomePage(Model model){
		model.addAttribute(new HomeModel());
		System.out.println("begin");
		spittleService.getRecentSPittles(11);
		return "home";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String addSpitterForm(@Valid HomeModel homeModel,BindingResult bindingResult,
			@RequestParam(value="image",required=false) MultipartFile image){
		if (bindingResult.hasErrors()) {
			return "home";
		}
		validateImage(image);
		saveImage("abc", image);
		return "redirect:/home/"+homeModel.getUserName();
	}
	
	public void validateImage(MultipartFile image){
		if (!image.getContentType().equals("image/jpeg")) {
			System.out.print("aaaaa");
		}
	}
	
	private void saveImage(String filename,MultipartFile image){
		try {
			File file = new File(filename);
			
			FileUtils.writeByteArrayToFile(file, image.getBytes());
			System.out.println(file.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET,value="/{username}")
	public String showSpitterProfile(@PathVariable String username,HomeModel homeModel){
		homeModel.setUserName(username);
		System.out.println(username);
		return "home";
	}
}
